package com.slj.controller;

import com.slj.DTO.BookQueryDTO;
import com.slj.entity.Book;
import com.slj.service.BookService;
import com.slj.uitil.FileUtil;
import com.slj.uitil.Page;
import com.slj.uitil.S;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/api/book")
@CrossOrigin("*")
@RequiredArgsConstructor
public class BookController {
    private static final Logger log = Logger.getLogger(BookController.class);
    private final BookService bookService;

    @PostMapping("/getBook")
    public S<Page<Book>> getBook(@RequestBody BookQueryDTO bookQueryDTO) {
        return bookService.getBook(bookQueryDTO);
    }
    /**
     * 删除书籍
     */
    @DeleteMapping("/deleteBook")
    public Integer deleteBook(@Param("id") Integer id) {
        log.info("接收到删除图书请求，id: " + id);
        return bookService.deleteBook(id);
    }


    /**
     * 添加书籍
     */
    @PostMapping("/addBook")
    public ResponseEntity<String> addBook(@RequestParam("bookName") String bookName, @RequestParam("author") String author,
                                          @RequestParam("publicationDate") String publicationDate,
                                          @RequestParam("price") String priceStr,
                                          @RequestParam("bookTypeId") Integer bookTypeId,
                                          @RequestParam("bookImageFile") MultipartFile bookImageFile) {

        // 记录请求到达
        log.info("接收到添加图书请求，书名: " + bookName + ", 作者: " + author);
        try {
            //转换日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date pubDate = sdf.parse(publicationDate);
            //转换价格
            BigDecimal price = new BigDecimal(priceStr);
            // 1. 保存图片文件
            String fileName = FileUtil.uploadFile(bookImageFile);
            // 2. 创建图书对象
            Book book = new Book();
            book.setBookName(bookName);
            book.setAuthor(author);
            book.setPublicationDate(pubDate);
            book.setPrice(price);
            book.setBookTypeId(bookTypeId);
            book.setCoverImageUrl(fileName);

            // 3. 保存到数据库
            int result = bookService.addBook(book);
            return result > 0
                    ? ResponseEntity.ok("添加成功")
                    : ResponseEntity.badRequest().body("添加失败");
        } catch (Exception e) {
            log.error("添加图书失败", e); // 记录异常
            return ResponseEntity.badRequest().body("错误: " + e.getMessage());
        }




    }
    /**
     * 根据id查询书籍
     */
    @GetMapping("/getBookById")
    public S<Book> getBookById(@Param("id") Integer id) {
        log.info("接收到查询图书请求，id: " + id);
        return bookService.getBookById(id);
    }

    /**
     * 修改书籍
     */
    @PostMapping("/updateBook")
    public Integer updateBook(
            @RequestParam("id") Integer id,
            @RequestParam("bookName") String bookName,
            @RequestParam("author") String author,
            @RequestParam("publicationDate") String publicationDate,
            @RequestParam("price") String priceStr,
            @RequestParam("bookTypeId") Integer bookTypeId,
            @RequestParam(value = "bookImageFile", required = false) MultipartFile bookImageFile // 改为可选
    ) {
        // 转换数据
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date pubDate = null;
        try {
            pubDate = sdf.parse(publicationDate);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        BigDecimal price = new BigDecimal(priceStr);

        // 1. 处理封面图片（可选）
        String fileName = null;
        if (bookImageFile != null && !bookImageFile.isEmpty()) {
            try {
                fileName = FileUtil.uploadFile(bookImageFile); // 仅当文件存在时上传
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        // 2. 更新图书信息
        Book book = new Book();
        book.setId(id);
        book.setBookName(bookName);
        book.setAuthor(author);
        book.setPublicationDate(pubDate);
        book.setPrice(price);
        book.setBookTypeId(bookTypeId);
        if (fileName != null) {
            book.setCoverImageUrl(fileName); // 仅更新新图片路径
        }

        return bookService.updateBook(book);
    }
}
